package com.zrz.util;

import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
    private static Graphics2D g = null;
    private static String imageUrl = File.separator + "usr" + File.separator + "local" + File.separator + "wine" + File.separator + "image" + File.separator;

    /**
     * 导入本地图片到缓冲区
     */
    public static BufferedImage loadImageLocal(File file) {
        try {
            return ImageIO.read(file);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static BufferedImage modifyImagetogeter(BufferedImage code, BufferedImage bg) {

        try {
            int w = code.getWidth()+300;
            int h = code.getHeight()+300;

            g = bg.createGraphics();
            g.drawImage(code, 905, 2193, w, h, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return bg;
    }

    /**
     * 生成新图片到本地
     */
    public static void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static String addImage(Integer userId) {
        String url = imageUrl + userId + "-tuiguang.jpg";
        File fileNew = new File(url);
        if (fileNew.exists()) {
            return url;
        }
        try {
            File file = ResourceUtils.getFile("classpath:tuiguang-bg.jpg");
            BufferedImage bg = loadImageLocal(file);
            BufferedImage code = loadImageLocal(new File(imageUrl + userId + ".jpg"));
            writeImageLocal(url, modifyImagetogeter(code, bg));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    public static void main(String[] args) {

        ImageUtil test = new ImageUtil();
        ImageUtil.addImage(16);
        File file=new File("d:/tuiguang.jpg");
        File file1=new File("d:/100.jpg");

        BufferedImage bg = test.loadImageLocal(file);
        BufferedImage code = test.loadImageLocal(file1);

        test.writeImageLocal("d:/new10.jpg", test.modifyImagetogeter(code, bg));
//        //将多张图片合在一起
        System.out.println("success");
    }
}
